package com.atguigu.flink.edu.app.dwd.log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.flink.edu.utils.DataFormatUtil;
import com.atguigu.flink.edu.utils.MyKafkaUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import javax.naming.Context;
import java.time.Duration;

public class DwdTrafficBaseLogSplit {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);
        /*//TODO 2.检查点相关设置
        //2.1 开启检查点
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        //2.2 设置检查点超时时间
        env.getCheckpointConfig().setCheckpointTimeout(6000L);
        //2.3 设置job取消之后检查点是否保留
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //2.4 设置两个检查点之间最小的时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
        //2.5 设置重启策略
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30),Time.seconds(3)));
        //2.6 设置状态后端
        env.setStateBackend(new HashMapStateB ackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop202:8020/gmall/ck");
        //2.7 设置操作hadoop的用户
        System.setProperty("HADOOP_USER_NAME","atguuigu");*/

        //TODO 3.从kafka的主题中读取日志数据
        //3.1 声明消费的主题以及消费者组
        String topic = "topic_log";
        String groupId = "dwd_traffic_log_split_group";
        //3.2 创建消费者对象
        KafkaSource<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);
        //3.3 消费数据 封装为流
        DataStreamSource<String> kafkaStrDS = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafka_source");

        //TODO 4.简单的ETL并对流中数据类型进行转换     脏数据写到侧输出流中
        //4.1 定义侧输出流标签
        OutputTag<String> dirtyTag = new OutputTag<String>("dirtyTag") {
        };
        //4.2 ETL以及转换
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
                        try {
                            JSONObject jsonObj = JSON.parseObject(jsonStr);
                            out.collect(jsonObj);
                        } catch (Exception e) {
                            //如果发生了异常，说明流中的数据不是标准的json，属于脏数据，放到侧输出流中
                            ctx.output(dirtyTag, jsonStr);
                        }
                    }
                }
        );
        jsonObjDS.print(">>>>");
        SideOutputDataStream<String> dirtyDS = jsonObjDS.getSideOutput(dirtyTag);
        dirtyDS.print("####");

        //TODO 5.将侧输出流中的脏数据写到kafka的主题中

        dirtyDS.sinkTo(
                MyKafkaUtil.getKafkaSink("dirty_data", "dirty")
        );
        //TODO 6.对新老访客标记进行修复    状态编程
        KeyedStream<JSONObject, String> keyedDS
                = jsonObjDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));
        SingleOutputStreamOperator<JSONObject> fixedDS = keyedDS.map(
                new RichMapFunction<JSONObject, JSONObject>() {
                    private ValueState<String> lastVisitDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<String> valueStateDescriptor
                                = new ValueStateDescriptor<String>("lastVisitDateState", String.class);
                        lastVisitDateState = getRuntimeContext().getState(valueStateDescriptor);
                    }

                    @Override
                    public JSONObject map(JSONObject jsonObj) throws Exception {
                        String isNew = jsonObj.getJSONObject("common").getString("is_new");
                        String lastVisitDate = lastVisitDateState.value();
                        Long ts = jsonObj.getLong("ts");
                        String curVisitDate = DataFormatUtil.toDate(ts);
                        if ("1".equals(isNew)) {

                            if (StringUtils.isEmpty(lastVisitDate)) {
                                lastVisitDateState.update(curVisitDate);

                            } else {
                                if (!lastVisitDate.equals(curVisitDate)) {
                                    isNew = "0";
                                    jsonObj.getJSONObject("common").put("is_new", isNew);
                                }
                            }
                        } else {
                            if (StringUtils.isEmpty(lastVisitDate)) {
                                Long yesterDayMS = ts - 24 * 60 * 60 * 1000;
                                String yesterDay = DataFormatUtil.toDate(yesterDayMS);
                                lastVisitDateState.update(yesterDay);
                            }
                        }
                        return jsonObj;
                    }
                }
        );
        OutputTag<String> errTag = new OutputTag<String>("errTag") {};
        OutputTag<String> startTag = new OutputTag<String>("startTag") {};
        OutputTag<String> videoTag = new OutputTag<String>("videoTag") {};
        OutputTag<String> displayTag = new OutputTag<String>("displayTag") {};
        OutputTag<String> actionTag = new OutputTag<String>("actionTag") {};

        //TODO 7.分流   错误日志-错误侧输出流 启动日志-启动侧输出流 曝光日志-曝光侧输出流 动作日志-动作侧输出流 页面日志-主流

        SingleOutputStreamOperator<String> pageStream =
                fixedDS.process(new ProcessFunction<JSONObject, String>() {
                    @Override
                    public void processElement(JSONObject jsonObject, Context ctx, Collector<String> out) throws Exception {
                        //处理err日志
                        JSONObject errJsonObject = jsonObject.getJSONObject("err");
                        JSONObject startJsonObject = jsonObject.getJSONObject("start");
                        JSONObject appVideoJsonObject = jsonObject.getJSONObject("appVideo");
                        JSONObject pageJsonObject = jsonObject.getJSONObject("page");

                        if (errJsonObject != null) {
                            ctx.output(errTag, errJsonObject.toJSONString());
                            jsonObject.remove("err");
                        }
                        //处理 start 日志
                        if (startJsonObject != null) {
                            JSONObject commonJsonObject = jsonObject.getJSONObject("common");
                            Long ts = jsonObject.getLong("ts");
                            JSONObject newJsonObject = new JSONObject();
                            newJsonObject.put("common",commonJsonObject);
                            newJsonObject.put("start",startJsonObject);
                            newJsonObject.put("ts",ts);
                            ctx.output(startTag, startJsonObject.toJSONString());
                        }
                        //处理 apppvideo 日志
                        //逻辑: 如果不是video日志,就获取 common,page,ts,display,actions
                        if (appVideoJsonObject != null) {
                            JSONObject commonJsonObject = jsonObject.getJSONObject("common");
                            Long ts = jsonObject.getLong("ts");
                            JSONObject newJsonObject = new JSONObject();
                            newJsonObject.put("common",commonJsonObject);
                            newJsonObject.put("appVideo",appVideoJsonObject);
                            newJsonObject.put("ts",ts);
                            ctx.output(videoTag, newJsonObject.toJSONString());
                        }
                        if (pageJsonObject != null) {
                            JSONObject commonJsonObject = jsonObject.getJSONObject("common");
                            Long ts = jsonObject.getLong("ts");
                            JSONArray displaysJsonArray = jsonObject.getJSONArray("displays");
                            JSONArray actionJsonArray = jsonObject.getJSONArray("actions");

                            //如果是曝光日志,就 输出到侧曝光流中
                            if (displaysJsonArray != null && displaysJsonArray.size() > 0) {
                                for (int i = 0; i < displaysJsonArray.size(); i++) {
                                    JSONObject displayJsonObject = displaysJsonArray.getJSONObject(i);
                                    JSONObject newJsonObject = new JSONObject();
                                    newJsonObject.put("common", commonJsonObject);
                                    newJsonObject.put("page", pageJsonObject);
                                    newJsonObject.put("ts", ts);
                                    newJsonObject.put("display", displayJsonObject);
                                    ctx.output(displayTag, newJsonObject.toJSONString());
                                }
                                jsonObject.remove("displays");
                            }
                            //如果是 行为日志,就输出到 侧动作流中
                            if (actionJsonArray != null && actionJsonArray.size() > 0) {
                                for (int i = 0; i < actionJsonArray.size(); i++) {
                                    JSONObject actionJsonObject = actionJsonArray.getJSONObject(i);
                                    JSONObject newJsonObject = new JSONObject();
                                    newJsonObject.put("common", commonJsonObject);
                                    newJsonObject.put("page", pageJsonObject);
                                    newJsonObject.put("action", actionJsonObject);
                                    ctx.output(actionTag, newJsonObject.toJSONString());
                                }
                                jsonObject.remove("action");
                            }
                            out.collect(jsonObject.toJSONString());
                        }
                    }
                });

        //TODO 8.将不同流的数据写到kafka的主题中
        SideOutputDataStream<String> errDS =pageStream.getSideOutput(errTag);
        SideOutputDataStream<String> startDS = pageStream.getSideOutput(startTag);
        SideOutputDataStream<String> displayDS = pageStream.getSideOutput(displayTag);
        SideOutputDataStream<String> actionDS = pageStream.getSideOutput(actionTag);
        SideOutputDataStream<String> videoDS = pageStream.getSideOutput(videoTag);
        pageStream.print(">>>");
        errDS.print("###");
        startDS.print("$$$");
        displayDS.print("&&&");
        actionDS.print("@@@");
        videoDS.print("播放");
        pageStream.sinkTo(MyKafkaUtil.getKafkaSink("dwd_traffic_page_log", "page"));
        errDS.sinkTo(MyKafkaUtil.getKafkaSink("dwd_traffic_err_log", "err"));
        videoDS.sinkTo(MyKafkaUtil.getKafkaSink("dwd_traffic_video_log","video"));
        startDS.sinkTo(MyKafkaUtil.getKafkaSink("dwd_traffic_start_log", "start"));
        displayDS.sinkTo(MyKafkaUtil.getKafkaSink("dwd_traffic_display_log", "display"));
        actionDS.sinkTo(MyKafkaUtil.getKafkaSink("dwd_traffic_action_log", "action"));
        env.execute();
    }
}
